import '@wangeditor/editor/dist/css/style.css' // 引入 css

import React, { useState, useEffect } from 'react'
import { Editor, Toolbar } from '@wangeditor/editor-for-react'
import { IDomEditor, IEditorConfig } from '@wangeditor/editor'
import { URL_PREFIX } from '@/constants'



type EditorProps = {
	changeHandler: (text: string) => void;
	initialValue?: string;
	height?: string | number;
	width?: string | number;
}

function MyEditor(props: EditorProps) {
	let initialValue = ''
	if (props.initialValue) {
		if (props.initialValue.startsWith('<') && props.initialValue.endsWith('>')) {
			initialValue = props.initialValue
		} else {
			initialValue = `<p>${props.initialValue}</p>`
		}
	} else {
		initialValue = '<p></p>'
	}
	const [editor, setEditor] = useState<IDomEditor | null>(null) // 存储 editor 实例
	const [html, setHtml] = useState(initialValue) // 编辑器内容
	const toolbarConfig = {}
	const editorConfig: Partial<IEditorConfig> = {
		placeholder: '请输入内容...',
		MENU_CONF: {
			uploadImage: {
				server: URL_PREFIX + '/file/upload',
				// form-data fieldName ，默认值 'wangeditor-uploaded-image'
				fieldName: 'file',

				// 单个文件的最大体积限制，默认为 2M
				maxFileSize: 2 * 1024 * 1024,

				// 最多可上传几个文件，默认为 100
				maxNumberOfFiles: 10,

				// 选择文件时的类型限制，默认为 ['image/*'] 。如不想限制，则设置为 []
				allowedFileTypes: ['image/*'],
				customInsert(res: any, insertFn: any) {
					const url = URL_PREFIX + '/images/' + res.data
					insertFn(url)
				},
				// 超时时间，默认为 10 秒
				timeout: 10 * 1000,
			}
		}
	}


	// 及时销毁 editor ，重要！
	useEffect(() => {
		return () => {
			if (editor == null) return
			editor.destroy()
			setEditor(null)
		}
	}, [editor])

	return (
		<>
			<div style={{ border: '1px solid #ccc', zIndex: 100 }}>
				<Toolbar
					editor={editor}
					defaultConfig={toolbarConfig}
					mode="default"
					style={{ borderBottom: '1px solid #ccc' }}
				/>
				<Editor
					defaultConfig={editorConfig}
					value={html}
					onCreated={setEditor}
					onChange={editor => {
						setHtml(editor.getHtml())
						props.changeHandler(editor.getHtml())
					}}
					mode="default"
					style={{ height: props.height ?? '500px', width: props.width, overflowY: 'hidden' }}
				/>
			</div>
		</>
	)
}

export default MyEditor